"""
Desc : 自定义函数调用
"""

import re
import datetime
import random
from datetime import date, timedelta, datetime

import cn2an as cn2an
import requests
import yaml
from jsonpath import jsonpath
from faker import Faker

from utils.cache_process.cache_control import CacheHandler, _cache_config
from utils.logging_tool.log_control import ERROR


class Context:
    """ 正则替换 """

    def __init__(self):
        self.faker = Faker(locale='zh_CN')

    def cache(self, regular_data):
        return CacheHandler.get_cache(regular_data)

    @classmethod
    def Ctest01(cls, index):
        if index == 0:
            return "shuchu"

    @classmethod
    def Ctest02(cls):
        return "shuchu2"

    @classmethod
    def Ctest03(cls, index, index2):
        if index == 0 and index2 == 0:
            return "shuchu3"
        else:
            return "啥也没有"

    def set_value(cls, value):

        return value
        # return cn2an.an2cn(value)

    @classmethod
    def random_int(cls, min_num=0, max_num=5000) -> int:
        """
        生成一个随机整数。

        :param min_num: 随机数范围的起始值（默认为0）
        :param max_num: 随机数范围的结束值（默认为5000）
        :return: 生成的随机整数
        """
        _data = random.randint(int(min_num), int(max_num))
        return _data

    def get_phone(self) -> int:
        """
        :return: 随机生成手机号码
        """
        phone = self.faker.phone_number()
        return phone

    def get_id_number(self) -> int:
        """

        :return: 随机生成身份证号码
        """

        id_number = self.faker.ssn()
        return id_number

    def get_female_name(self) -> str:
        """

        :return: 女生姓名
        """
        female_name = self.faker.name_female()
        return female_name

    def get_male_name(self) -> str:
        """

        :return: 男生姓名
        """
        male_name = self.faker.name_male()
        return male_name

    def get_email(self) -> str:
        """

        :return: 生成邮箱
        """
        email = self.faker.email()
        return email

    @classmethod
    def self_operated_id(cls):
        """自营店铺 ID """
        operated_id = 212
        return operated_id

    @classmethod
    def get_time(cls) -> str:
        """
        计算当前时间
        :return:
        """
        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return now_time

    @classmethod
    def today_date(cls):
        """获取今日0点整时间"""

        _today = date.today().strftime("%Y-%m-%d") + " 00:00:00"
        return str(_today)

    @classmethod
    def time_after_week(cls):
        """获取一周后12点整的时间"""

        _time_after_week = (date.today() + timedelta(days=+6)).strftime("%Y-%m-%d") + " 00:00:00"
        return _time_after_week

    @classmethod
    def host(cls) -> str:
        from utils import config
        """ 获取接口域名 """
        return config.host

    def bank_host(cls) -> str:
        from utils import config
        """ 获取接口域名 """
        return config.bank_host

    def app_host(cls) -> str:
        from utils import config
        """ 获取接口域名 """
        return config.app_host


def json_extract(js_path, res):
    """ 提取 sql中的 json 数据 """
    _json_data = jsonpath(res, js_path)[0]
    if _json_data is False:
        raise ValueError(f"sql中的jsonpath获取失败 {res}, {js_path}")
    return _json_data


def sql_regular(value, res=None):
    """
    这里处理sql中的依赖数据，通过获取接口响应的jsonpath的值进行替换
    :param res: jsonpath使用的返回结果
    :param value:
    :return:
    """
    sql_json_list = re.findall(r"\$jsonpath{(.*?)}\$", value)

    for i in sql_json_list:
        pattern = re.compile(r'\$jsonpath{' + i.replace('$', "\$").replace('[', '\[') + r'}\$')
        key = str(json_extract(i, res))
        value = re.sub(pattern, key, value, count=1)

    return value


def cache_regular_exist(value):
    """
    通过正则的方式，读取缓存中的内容,若缓存中的key对应的值不存在或key在缓存不存在，则不进行替换
    例：$cache{login_init}
    :param value: 要处理的字符串
    :return: 替换后的字符串
    """
    # 正则获取 $cache{login_init}中的值 --> login_init
    regular_dates = re.findall(r"\$cache\{(.*?)\}", value)
    # 拿到的是一个list，循环数据
    for regular_data in regular_dates:
        value_types = ['int:', 'bool:', 'list:', 'dict:', 'tuple:', 'float:']
        if any(i in regular_data for i in value_types) is True:
            value_types = regular_data.split(":")[0]
            regular_data = regular_data.split(":")[1]
            pattern = re.compile(r'\'\$cache\{' + value_types.split(":")[0] + ":" + regular_data + r'\}\'')
        else:
            pattern = re.compile(
                r'\$cache\{' + regular_data.replace('$', "\$").replace('[', '\[') + r'\}'
            )
        if regular_data in _cache_config.keys():
            cache_data = _cache_config[regular_data]
            if cache_data is not None:
                value = re.sub(pattern, str(cache_data), value)

    return value


def cache_regular(value):
    from utils.cache_process.cache_control import CacheHandler

    """
    通过正则的方式，读取缓存中的内容
    例：$cache{login_init}
    :param value:
    :return:
    """
    # 正则获取 $cache{login_init}中的值 --> login_init
    regular_dates = re.findall(r"\$cache\{(.*?)\}", value)

    # 拿到的是一个list，循环数据
    for regular_data in regular_dates:
        value_types = ['int:', 'bool:', 'list:', 'dict:', 'tuple:', 'float:']
        if any(i in regular_data for i in value_types) is True:
            value_types = regular_data.split(":")[0]
            regular_data = regular_data.split(":")[1]
            # pattern = re.compile(r'\'\$cache{' + value_types.split(":")[0] + r'(.*?)}\'')
            pattern = re.compile(r'\'\$cache\{' + value_types.split(":")[0] + ":" + regular_data + r'\}\'')
        else:
            pattern = re.compile(
                r'\$cache\{' + regular_data.replace('$', "\$").replace('[', '\[') + r'\}'
            )
        try:
            # cache_data = Cache(regular_data).get_cache()
            cache_data = CacheHandler.get_cache(regular_data)
            # 使用sub方法，替换已经拿到的内容
            value = re.sub(pattern, str(cache_data), value)
        except Exception:
            raise
    return value


# TODO：优先级0 希望匹配到了数据后，在匹配到的数据中若满足cache_regular(),sql_regular()，则也进行执行
def regular(target):
    """
    新版本
    使用正则替换请求数据
    :return:
    """
    try:
        regular_pattern = r'\${{(.*?)}}'
        while re.findall(regular_pattern, target):
            key = re.search(regular_pattern, target).group(1)
            value_types = ['int:', 'bool:', 'list:', 'dict:', 'tuple:', 'float:']
            if any(i in key for i in value_types) is True:
                func_name = key.split(":")[1].split("(")[0]
                value_name = key.split(":")[1].split("(")[1][:-1]
                if value_name == "":
                    value_data = getattr(Context(), func_name)()
                else:
                    value_data = getattr(Context(), func_name)(*value_name.split(","))
                regular_int_pattern = r'\'\${{(.*?)}}\''
                target = re.sub(regular_int_pattern, str(value_data), target, 1)
            else:
                func_name = key.split("(")[0]
                value_name = key.split("(")[1][:-1]
                if value_name == "":
                    value_data = getattr(Context(), func_name)()
                else:
                    value_data = getattr(Context(), func_name)(*value_name.split(","))
                    # value_args = [eval(arg) for arg in value_name.split(",")]
                    # value_data = getattr(Context(), func_name)(*value_args)

                target = re.sub(regular_pattern, str(value_data), target, 1)
        return target

    except AttributeError:
        ERROR.logger.error("未找到对应的替换的数据, 请检查数据是否正确 %s", target)
        raise
    except IndexError:
        ERROR.logger.error("yaml中的 ${{}} 函数方法不正确，正确语法实例：${{get_time()}}")
        raise


if __name__ == '__main__':
    a = Context().random_int(20, 50)
    t = 'abc${{random_int(20,50)}}abc'
    print(cn2an.an2cn('1'))